﻿using System.Linq;
using System.Reflection;
using System.Threading.Tasks;
using Common;
using Common.DataModels;
using Extensions.Attribute;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Controllers;
using Microsoft.AspNetCore.Mvc.Filters;

namespace Extensions.Filters;
//自定义全局的模型验证反正  注册在全局 所有  全局都会调用
public class FlunetValidationFilter:IAsyncActionFilter
{
    //public override void OnActionExecuting(ActionExecutingContext context)
    //{
    //    if (!context.ModelState.IsValid)
    //    {
    //        var errors = context.ModelState.Values.SelectMany(p => p.Errors).Select(p => p.ErrorMessage).ToList();
    //        var errorMessage = string.Join("\r\n", errors);
    //        var messageMode = MessageModel<string>.Fail("模型验证失败", errorMessage);
    //         执行action 之前
    //        context.Result = new ContentResult()
    //        {
    //            Content = JsonHelper.SerializeObject(messageMode)
    //        };
          
    //    }

    //}
    public async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)
    {
        
        // 如果验证失败  那么就返回失败信息
        if (!context.ModelState.IsValid)
        {
            var errors = context.ModelState.Values.SelectMany(p => p.Errors).Select(p => p.ErrorMessage).ToList();
            var errorMessage = string.Join("\r\n", errors);
            var messageMode = MessageModel<string>.Fail("模型验证失败", errorMessage);
            context.Result = new ContentResult()
                {
                    Content = JsonHelper.SerializeObject(messageMode)
                };
        }
        else
        {
            // 模型验证成功  继续执行接下去的actonfilter
            await next.Invoke();
        }
        
        // 和中间件管道一样  next.invoke后面就是一层一层的返回了
    }
}